// 工具函数文件，如处理数据格式，数字动态滚动等
import Decimal from 'decimal.js'
import { isNull } from './data-processing'
import dayjs from 'dayjs'
import { FileListType } from '@renderer/types/global'

// 时间过滤 只能选小于等于今天
export function pickerOptions(time: any) {
  return time.getTime() > Date.now()
}
//验证数字 保留2位小数
/**
 *
 * @param value value值
 * @param fieldName 对应的过滤字段
 * @param formData 字段对象
 * @param figures 保留的位数默认为2
 * @returns
 */
export function validatorNumber(value: any, fieldName: string, formData: any, figures = 2) {
  if (!value) {
    if (fieldName.split(',').length > 1) {
      return (formData[fieldName.split(',')[0]][fieldName.split(',')[1]] = value)
    } else {
      return (formData[fieldName] = value)
    }
  }
  value =
    value
      .replace(/[^-?\d^\\.]+/g, '')
      .replace(/^-?\./, '0.')
      .match(`-?\\d*(\\.?\\d{0,${figures}})`)[0] || ''
  // 判断是否数组
  if (fieldName.split(',').length > 1) {
    formData[fieldName.split(',')[0]][fieldName.split(',')[1]] = value || ''
  } else {
    formData[fieldName] = value || ''
  }
}

//验证数字-正整数
/**
 *
 * @param value value值
 * @param fieldName 对应的过滤字段
 * @param formData 字段对象
 * @returns
 */
export function validatorInteger(value: any, fieldName: string, formData: any) {
  if (!value) {
    if (fieldName.split(',').length > 1) {
      formData[fieldName.split(',')[0]][fieldName.split(',')[1]] = parseInt(value || 0)
    } else {
      formData[fieldName] = parseInt(value || 0)
    }
  }
  value = value.replace(/[^-?\d^]+/g, '')

  //  判断是否数组
  if (fieldName.split(',').length > 1) {
    formData[fieldName.split(',')[0]][fieldName.split(',')[1]] = parseInt(value || 0)
  } else {
    formData[fieldName] = parseInt(value || 0)
  }
}

//验证数字-正负整数
/**
 *
 * @param value value值
 * @param fieldName 对应的过滤字段
 * @param formData 字段对象
 * @returns
 */
export function validatorNgtAndPst(value: any, fieldName: string, formData: any) {
  value = value.replace(/[^-?\d^]+/g, '').match(`-?\\d*`)[0] || ''

  // // 判断是否数组
  if (fieldName.split(',').length > 1) {
    formData[fieldName.split(',')[0]][fieldName.split(',')[1]] = value
  } else {
    formData[fieldName] = value
  }
}

// 正数
export function positiveNumber(value: any, fieldName: string, formData: any) {
  if (!value) return value
  validatorNumber(value, fieldName, formData)
  formData[fieldName] = value < 0 ? 0 : formData[fieldName]
}

/**
 * 选择时间赋值
 * @param dates 区间对象
 * @param startField 开始时间
 * @param endField 结束时间
 * @param obj JSON对象
 */
export function selectDates(dates: any, startField: string, endField: string, obj: any) {
  if (dates && dates.length > 0) {
    obj[startField] = dates[0]
    obj[endField] = dates[1]
  } else {
    obj[startField] = ''
    obj[endField] = ''
  }
}

/**
 * 保留2位小数-事件对象版
 * @param e model对象
 * @param figures 保留的小数
 * @param required 是否必填
 * @param defaultNum 必填填空值
 */
export function blurToFixed2(e: any, figures = 2, required = false, defaultNum = 0) {
  if (!e.target.value) {
    e.target.value = required ? defaultNum : ''
    return
  }
  e.target.value = parseFloat(e.target.value).toFixed(figures)
}

/**
 * 保留2位小数-数据赋值版(可触发校验)
 * @param formData 修改对象
 * @param fieldName 对应的过滤字段
 * @param figures 保留的小数
 * @param required 是否必填
 * @param defaultNum 必填填空值
 * @param maxNum 最大值
 */
export function blurToFixedData(
  formData: any,
  fieldName: string,
  figures = 2,
  required = false,
  defaultNum = 0,
  maxNum?: number
) {
  if (!formData[fieldName]) {
    formData[fieldName] = required ? defaultNum : ''
    return
  }
  let curNum = parseFloat(parseFloat(formData[fieldName]).toFixed(figures))
  if ((maxNum || maxNum === 0) && curNum > maxNum) {
    curNum = maxNum
  }
  formData[fieldName] = curNum
}

//四舍五入保留2位小数
export function decimalRound(
  num: number | string,
  figures = 2,
  showZero?: boolean
): number | string {
  if (isNull(num)) return num
  if (num) {
    num = Number(num) + 0.00000001 //添加精度
  }
  num = new Decimal(num).toFixed(figures, Decimal.ROUND_HALF_UP)
  if (!showZero) num = Number(num)

  // 后台保留4位小数导致前端变成-0的值
  if ((num as any) == 0 && (num + '').includes('-')) {
    return (num + '').replace('-', '')
  }
  return num
}

//切割金额-千分位
export function formatPrice(money: number | string = 0, figures: number = 1, showZero?: boolean) {
  if (showZero) money = decimalRound(money || 0, figures, showZero) + ''
  else money = decimalRound(money || 0, figures) + ''
  const oldMoney = money.split('.')
  const resultMoney = money + ''
  const isNaNMoney = Number(money)
  if (isNaN(isNaNMoney)) {
    return money
  }
  // 判断正负数
  if (money.slice(0, 1) != '-') {
    money = Number(money) + ''
  } else {
    money = Number(money.slice(1, money.length)) + ''
  }
  const str = money.split('.')
  money = str[0]

  // 去掉第一个0
  if (money.slice(0, 1) === '0') {
    if (money.length > 1) {
      money = money.substring(1, money.length)
    }
  }
  let result = ''

  // 实现科学计数法，每个三位加一个","
  while (money.length >= 4) {
    result = ',' + money.slice(-3) + result
    money = money.slice(0, money.length - 3)
  }

  if (money) {
    result = money + result
  }
  for (let x = 0; x < oldMoney.length; x++) {
    if (x != 0) {
      if (x == 1 && figures) {
        oldMoney[x] = oldMoney[x].slice(0, figures)
      }
      result = result + '.' + oldMoney[x]
    }
  }
  if (resultMoney.slice(0, 1) == '-' && result != '0') {
    result = '-' + result
  }
  // 后台保留4位小数导致前端变成-0的值
  if ((result as any) == 0 && result.includes('-')) {
    return result.replace('-', '')
  }
  return result
}

// 根据字符串随机选一个颜色
export function generateColor(name: any) {
  let hash = 0
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash)
  }
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
  const color = colors[Math.abs(hash % colors.length)]
  return color
}

//根据时间日期返回时间提示
export function showTimeByDate(time: string) {
  const data = new Date(time)
  const dateTimeStamp = data.getTime()
  const minute = 1000 * 60 //把分，时，天，周，半个月，一个月用毫秒表示
  const hour = minute * 60
  const day = hour * 24
  const week = day * 7
  const month = day * 30
  const year = month * 12
  const now = new Date().getTime() //获取当前时间毫秒
  const diffValue = now - dateTimeStamp //时间差

  let result = ''
  if (diffValue < 0) {
    result = '' + '刚刚'
  }
  const minC: any = diffValue / minute //计算时间差的分，时，天，周，月
  const hourC: any = diffValue / hour
  const dayC: any = diffValue / day
  const weekC: any = diffValue / week
  const monthC: any = diffValue / month
  const yearC: any = diffValue / year

  if (yearC >= 1) {
    result = ' ' + parseInt(yearC) + '年前'
  } else if (monthC >= 1 && monthC < 12) {
    result = ' ' + parseInt(monthC) + '月前'
  } else if (weekC >= 1 && weekC < 5 && dayC > 6 && monthC < 1) {
    result = ' ' + parseInt(weekC) + '周前'
  } else if (dayC >= 1 && dayC <= 6) {
    result = ' ' + parseInt(dayC) + '天前'
  } else if (hourC >= 1 && hourC <= 23) {
    result = ' ' + parseInt(hourC) + '小时前'
  } else if (minC >= 1 && minC <= 59) {
    result = ' ' + parseInt(minC) + '分钟前'
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = '刚刚'
  }
  return result
}

//切割金额
export function formatterPrice(value: number) {
  return formatPrice(value || 0, 1, true)
}

// 百分比
export function formatterRate(value: any) {
  return `${formatPrice(value || 0, 1, true)}%`
}

// 精切到天
export function formatterDate(value: any) {
  return value ? dayjs(value).format('YYYY-MM-DD') : ''
}

// 精切到秒
export function formatterTime(value: any) {
  return value ? dayjs(value).format('YYYY-MM-DD') : ''
}

// 精切到月
export function formatterMonth(value: any) {
  return value ? dayjs(value).format('YYYY-MM') : ''
}

// 文件下载
export function downloadFile(FileUrl: string) {
  const url = FileUrl
  const a = document.createElement('a')
  a.href = url
  a.download = '' // 设置为空字符串可触发下载；可指定文件名，如 'file.pdf'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 下载二进制文件
export function downloadByteFile(temp: FileListType) {
  fetch(temp.fileUrl).then(async (response) => {
    const blob = await response.blob()

    const disposition = response.headers.get('Content-Disposition')

    if (disposition && disposition.includes('filename=')) {
      const match = disposition.match(/filename="?([^"]+)"?/)
      if (match?.[1]) temp.fileName = match[1]
    }

    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = temp.fileName
    a.click()
    a.remove()
    window.URL.revokeObjectURL(url)
  })
}
